package com.jsy.mini12306.manage.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsy.mini12306.common.entity.*;
import com.jsy.mini12306.manage.entity.TrainPassStationExcel;
import com.jsy.mini12306.manage.mapper.TrainPassStationMapper;
import com.jsy.mini12306.manage.service.*;
import com.jsy.mini12306.manage.util.PinyinUtil;
import com.jsy.mini12306.manage.vo.TrainVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;


/**
 * 车次行程列表(TrainPassStation)表服务实现类
 *
 * @author: SongyangJi
 * @since: 2021-09-03 03:02:10
 * @description:
 */

@Slf4j
@Service("trainPassStationService")
public class TrainPassStationServiceImpl extends ServiceImpl<TrainPassStationMapper, TrainPassStation> implements TrainPassStationService {

    @Resource
    TrainService trainService;

    @Resource
    TrainPassStationService trainPassStationService;

    @Resource
    TrainPatternService trainPatternService;

    @Resource
    ManageStationService manageStationService;

    @Resource
    TrainCalendarService trainCalendarService;

    @Resource
    TrainSeatService trainSeatService;

    private TrainPassStation wrapTrainPassStationExcelToTrainPassStation(Integer trainId, TrainPassStationExcel trainPassStationExcel) {
        TrainPassStation trainPassStation = trainPassStationExcel.wrap();
        trainPassStation.setTrainId(trainId);
        String stationName = trainPassStationExcel.getStationName();
        Station station = manageStationService.queryByStationName(stationName);

        /*
         * 真实情况是有station的，
         */
        if (station == null) {
            Station build = Station.builder()
                    .stationName(stationName)
                    .city(stationName)
                    .alphabetical(PinyinUtil.getPinyin(stationName, ""))
                    .build();
            manageStationService.save(build);
            station = build;
        }

        trainPassStation.setStationId(manageStationService.queryByStationName(trainPassStationExcel.getStationName()).getStationId());
        trainPassStation.setStation(station);
        return trainPassStation;
    }

    @Override
    public List<TrainPassStation> saveBatchTrainPassStationsFromExcel(Integer trainId, InputStream inputStream) {
        ArrayList<TrainPassStation> trainPassStations = new ArrayList<>();
        ExcelReader excelReader = EasyExcel.read(inputStream, TrainPassStationExcel.class, new AnalysisEventListener<TrainPassStationExcel>() {
            @Override
            public void invoke(TrainPassStationExcel trainPassStationExcel, AnalysisContext analysisContext) {
//                trainPassStationMapper.insert(wrapTrainPassStationExcelToTrainPassStation(trainId, trainPassStationExcel));
//                System.out.println(wrapTrainPassStationExcelToTrainPassStation(trainId, trainPassStationExcel));
                trainPassStations.add(wrapTrainPassStationExcelToTrainPassStation(trainId, trainPassStationExcel));
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
        }).build();
        // 读取sheet0
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        // 将 sheet 写入 Reader
        excelReader.read(readSheet);
        return trainPassStations;
    }

    @Transactional
    @Override
    public void saveNewTrain(TrainVO trainVO, InputStream inputStream) {

        TrainPattern trainPattern = trainPatternService.getOne(new QueryWrapper<TrainPattern>()
                .eq("train_pattern_name", trainVO.getTrainPatternName()));

        List<TrainPassStation> trainPassStations = saveBatchTrainPassStationsFromExcel(null, inputStream);
        String stationName1 = trainPassStations.get(0).getStation().getStationName();
        String stationName2 = trainPassStations.get(trainPassStations.size() - 1).getStation().getStationName();

        Train train = Train.builder()
                .trainName(trainVO.getTrainName())
                .trainPatternId(trainPattern.getTrainPatternId())
                .distance(trainVO.getDistance())
                .type(trainVO.getType())
                .manager(trainVO.getManager())
                .startStationName(stationName1)
                .endStationName(stationName2)
                .build();
        // 列车 入库
        trainService.save(train);
        Integer trainId = train.getTrainId();
//        System.out.println("new Id: "+trainId);
        trainPassStations.forEach(trainPassStation -> {
            trainPassStation.setTrainId(trainId);
        });
        // 经停站入库
        trainPassStationService.saveBatch(trainPassStations);

        // 运行日历入库
        LocalDate startWorkingDate = trainVO.getStartWorkingDate();
        for (int i = 0; i < 15; i++) { // 默认 15 天
            LocalDate localDate = startWorkingDate.plusDays(i);
            TrainCalendar calendar = new TrainCalendar(trainId, localDate);
            trainCalendarService.save(calendar);
        }
        // 座位信息入库
        Map<SeatType, Integer> seats = trainVO.getSeats();
        List<TrainSeat> trainSeats = new ArrayList<>();
        seats.forEach((seatType, integer) -> {
            trainSeats.add(new TrainSeat(trainId,seatType,integer));
        });
        trainSeatService.saveBatch(trainSeats);

    }
}
